package xyz.sicau.blog.filter;

import xyz.sicau.blog.utils.JwtUtils;
import xyz.sicau.blog.utils.UserThreadLocal;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.HashMap;

@WebFilter(urlPatterns = "/user/set/*", filterName = "usernewFilter")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

//    @Override
//    public void destroy() {
//        Filter.super.destroy();
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        String usertoken = servletRequest.getParameter("usertoken");
//        // 还没加时间校验
//        if (usertoken != null) {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } else {
//            System.out.println("UserFilter拦截了一条请求");
//        }
//    }

    @Override
    public void destroy() {
        UserThreadLocal.remove();
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String usertoken = servletRequest.getParameter("usertoken");
        int userIdByToken = JwtUtils.getUserIdByToken(usertoken);
        String username = JwtUtils.getUserNameByToken(usertoken);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", Integer.toString(userIdByToken));
        map.put("username", username);
        UserThreadLocal.put(map);

        // 还没加时间校验
        if (usertoken != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            System.out.println("UserFilter拦截了一条请求");
        }
    }
}
